package com.chongyahhh.security.security.configs.verification;

import com.chongyahhh.security.security.common.CommonUser;
import com.chongyahhh.security.security.common.UserAuthenticationService;
import com.chongyahhh.security.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * @Author chongyahhh
 * 验证码认证服务支持
 */
@Component
public class VerificationAuthenticationProvider implements AuthenticationProvider {

    private final UserAuthenticationService userAuthenticationService;

    private final String PASSWORD_ERROR = "用户名或密码错误";

    @Autowired
    public VerificationAuthenticationProvider(UserAuthenticationService userAuthenticationService) {
        this.userAuthenticationService = userAuthenticationService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        CommonUser user = (CommonUser)userAuthenticationService.loadUserUnderVerification(username);

        // 判断密码正误在这里
        if(!user.getPassword().equals(MD5Util.getMD5String(password + "{" + user.getSalt() + "}"))){
            throw new BadCredentialsException(PASSWORD_ERROR);
        }

        return new VerificationAuthentication(username, password, user.getUserId(), user.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        // 该 Provider 支持验证 VerificationAuthentication 和 UsernamePasswordAuthenticationToken
        return VerificationAuthentication.class.isAssignableFrom(aClass) || UsernamePasswordAuthenticationToken.class.isAssignableFrom(aClass);
    }
}
